package com.weishuang.monitor.leader.config.client;

import cn.hutool.json.JSONUtil;
import com.weishuang.monitor.leader.commons.entity.Result;
import com.weishuang.monitor.leader.commons.enums.ECODE;
import com.weishuang.monitor.leader.commons.enums.RCODE;
import com.weishuang.monitor.leader.commons.jwt.JWTInfo;
import com.weishuang.monitor.leader.commons.jwt.JwtTokenUtil;
import com.weishuang.monitor.leader.commons.utils.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
public class ClientAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    /**
     * 登陆成功返回token
     * @param httpServletRequest
     * @param httpServletResponse
     * @param authentication
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        ClientAuthenticationToken authentication1 = (ClientAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        ClientUserDetails principal = (ClientUserDetails) authentication1.getPrincipal();
        JWTInfo jwtInfo = new JWTInfo(principal.getUsername(),principal.getSystemName());
        try {
            String token = jwtTokenUtil.generateToken(jwtInfo);
            Result success = ResultUtils.success(RCODE.LOGIN_SUCCESS, token);
            httpServletResponse.setStatus(200);
            httpServletResponse.setHeader("Content-type","application/json;charset=UTF-8");
            httpServletResponse.getWriter().write(JSONUtil.toJsonPrettyStr(success));
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            Result error = ResultUtils.error(ECODE.ERROR_SERVER);
            httpServletResponse.setStatus(500);
            httpServletResponse.setHeader("Content-type","application/json;charset=UTF-8");
            httpServletResponse.getWriter().write(JSONUtil.toJsonPrettyStr(error));
        }
    }
}
